<!-- src/views/system/Config.vue -->
<script setup>
import {ref, onMounted, reactive, computed} from 'vue'
import { useConfigStore } from '@/stores/configStore'
import { ElMessage, ElMessageBox } from 'element-plus'

const configStore = useConfigStore()
const publicConfigVisible = ref(false)
const publicConfigData = ref({})
// 配置列表数据
const configList = ref([])
// 控制编辑弹窗
const dialogVisible = ref(false)
// 当前编辑的配置项
const currentConfig = ref({})
// 加载状态
const loading = ref(false)

// 历史记录相关
const historyVisible = ref(false)
const historyList = ref([])
const historyLoading = ref(false)

// 分页信息
const pageInfo = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 历史记录筛选条件
const historyFilter = reactive({
  key: '',
  operator: '',
  startDate: '',
  endDate: ''
})

// 获取所有配置（分页）
const fetchConfigList = async () => {
  try {
    loading.value = true
    const params = {
      pageNumber : pageInfo.page,
      pageSize: pageInfo.size
    }

    // 使用分页接口获取配置列表
    const response = await configStore.getConfigListWithPagination(params)
    if (response && response.code === 200) {
      configList.value = response.data.records || []
      pageInfo.total = response.data.total || response.data.totalRow || 0
    } else {
      throw new Error(response?.message || '获取配置列表失败')
    }
  } catch (err) {
    console.error('获取配置失败详细信息:', err)
    ElMessage.error('获取配置失败: ' + (err.message || '网络错误'))
    // 出错时清空列表
    configList.value = []
    pageInfo.total = 0
  } finally {
    loading.value = false
  }
}

// 编辑配置
const handleEdit = (row) => {
  currentConfig.value = {
    id: row.id,
    configKey: row.configKey || row.config_key,
    configValue: row.configValue || row.config_value,
    configDesc: row.configDesc || row.config_desc,
    createdTime: row.createdTime || row.created_time,
    updatedTime: row.updatedTime || row.updated_time,
    en: row.en
  }
  dialogVisible.value = true
}

// 保存配置
const saveConfig = async () => {
  try {
    const configToUpdate = {
      id: currentConfig.value.id,
      configKey: currentConfig.value.configKey,
      configValue: currentConfig.value.configValue,
      configDesc: currentConfig.value.configDesc,
      createdTime: currentConfig.value.createdTime,
      updatedTime: currentConfig.value.updatedTime,
      en: currentConfig.value.en
    }

    await configStore.updateConfig(configToUpdate)
    dialogVisible.value = false
    fetchConfigList()
  } catch (err) {
    ElMessage.error('保存配置失败: ' + (err.message || '网络错误'))
  }
}

// 刷新缓存
const refreshCache = async () => {
  try {
    await ElMessageBox.confirm('确定要刷新配置缓存吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await configStore.refreshCache()
    fetchConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('刷新缓存失败: ' + (error.message || '网络错误'))
    }
  }
}

// 查看公共配置
const viewPublicConfig = async () => {
  try {
    await configStore.getPublicConfig()
    publicConfigData.value = configStore.publicConfig
    publicConfigVisible.value = true
    ElMessage.success('获取公共配置成功')
  } catch (err) {
    ElMessage.error('获取公共配置失败: ' + (err.message || '网络错误'))
  }
}

// 环境选项
const envOptions = [
  { label: '生产环境', value: 'prod' },
  { label: '测试环境', value: 'test' },
  { label: '开发环境', value: 'dev' }
]

// 当前环境
const currentEnv = ref('prod')

// 环境切换
const switchEnv = async (env) => {
  currentEnv.value = env
  pageInfo.page = 1 // 切换环境时重置到第一页
  await fetchConfigList()
}

// 查看历史记录（带筛选）
const viewHistory = async () => {
  try {
    historyLoading.value = true
    historyVisible.value = true

    const params = {
      page: configStore.pageInfo.page,
      size: configStore.pageInfo.size,
      key: historyFilter.key,
      operator: historyFilter.operator,
      startDate: historyFilter.startDate,
      endDate: historyFilter.endDate
    }

    await configStore.getConfigHistory(params)
    historyList.value = configStore.historyList
  } catch (err) {
    ElMessage.error('获取历史记录失败: ' + (err.message || '网络错误'))
  } finally {
    historyLoading.value = false
  }
}

// 重置筛选条件
const resetFilter = () => {
  historyFilter.key = ''
  historyFilter.operator = ''
  historyFilter.startDate = ''
  historyFilter.endDate = ''
  viewHistory()
}

// 导出配置
const exportConfig = async () => {
  try {
    await configStore.getAllConfig()
    const mappedData = configStore.configList.map(item => ({
      config_key: item.configKey || item.config_key,
      config_value: item.configValue || item.config_value,
      config_desc: item.configDesc || item.config_desc,
      created_time: item.createdTime || item.created_time,
      updated_time: item.updatedTime || item.updated_time,
      en: item.en
    }))

    const dataStr = JSON.stringify(mappedData, null, 2)
    const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr)

    const exportFileDefaultName = `config_${new Date().toISOString().slice(0, 10)}.json`

    const linkElement = document.createElement('a')
    linkElement.setAttribute('href', dataUri)
    linkElement.setAttribute('download', exportFileDefaultName)
    linkElement.click()

    ElMessage.success('配置导出成功')
  } catch (err) {
    ElMessage.error('配置导出失败: ' + (err.message || '网络错误'))
  }
}

// 导入配置
const importConfig = async (file) => {
  try {
    const reader = new FileReader()
    reader.onload = async (e) => {
      try {
        const configData = JSON.parse(e.target.result)

        const mappedData = configData.map(item => ({
          id: item.id,
          config_key: item.config_key,
          config_value: item.config_value,
          config_desc: item.config_desc,
          created_time: item.created_time,
          updated_time: item.updated_time,
          en: item.en
        }))

        await ElMessageBox.confirm(
            `确定要导入 ${mappedData.length} 个配置项吗？这将覆盖现有配置。`,
            '导入确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )

        let successCount = 0
        for (const config of mappedData) {
          try {
            await configStore.updateConfig(config)
            successCount++
          } catch (err) {
            console.error('导入配置失败:', config, err)
          }
        }

        ElMessage.success(`成功导入 ${successCount}/${mappedData.length} 个配置项`)
        fetchConfigList()
      } catch (err) {
        ElMessage.error('解析配置文件失败: ' + (err.message || '文件格式错误'))
      }
    }
    reader.readAsText(file.raw)
  } catch (err) {
    ElMessage.error('配置导入失败: ' + (err.message || '网络错误'))
  }
}

// 格式化公共配置数据用于表格显示
const formatPublicConfigData = computed(() => {
  if (!publicConfigData.value) return []
  return Object.keys(publicConfigData.value).map(key => ({
    key,
    value: publicConfigData.value[key]
  }))
})


// 配置列表分页变化处理
const handlePageChange = (val) => {
  pageInfo.page = val
  fetchConfigList()
}

// 配置列表每页条数变化处理
const handleSizeChange = (val) => {
  pageInfo.size = val
  pageInfo.page = 1
  fetchConfigList()
}

// 历史记录分页变化处理
const handleHistoryPageChange = (val) => {
  configStore.pageInfo.page = val
  viewHistory()
}

onMounted(() => {
  fetchConfigList()
})
</script>

<template>
  <div>
    <!-- 环境切换 -->
    <div style="margin-bottom: 20px;">
      <el-radio-group v-model="currentEnv" @change="switchEnv">
        <el-radio-button
            v-for="env in envOptions"
            :key="env.value"
            :value="env.value"
        >
          {{ env.label }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <div>
      <div style="margin-bottom: 20px;">
        <el-button @click="exportConfig" type="info" style="margin-right: 10px;">
          导出配置
        </el-button>

        <el-upload
            action="#"
            :auto-upload="false"
            :on-change="importConfig"
            accept=".json"
            style="display: inline-block;"
        >
          <el-button type="warning">
            导入配置
          </el-button>
        </el-upload>
      </div>
    </div>

    <div style="margin-bottom: 20px;">
      <el-button
          @click="fetchConfigList"
          type="primary"
          :loading="loading"
          style="margin-right: 10px;"
      >
        刷新列表
      </el-button>
      <el-button
          @click="refreshCache"
          type="success"
          style="margin-right: 10px;"
      >
        刷新缓存
      </el-button>
      <el-button
          @click="viewPublicConfig"
          type="info"
          style="margin-right: 10px;"
      >
        查看公共配置
      </el-button>
      <el-button
          @click="viewHistory"
          type="warning"
      >
        历史记录
      </el-button>
    </div>

    <el-table :data="configList" border v-loading="loading">
      <el-table-column prop="configKey" label="配置键" width="200"></el-table-column>
      <el-table-column prop="configValue" label="配置值"></el-table-column>
      <el-table-column prop="configDesc" label="描述" width="200"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div style="margin-top: 20px; display: flex; justify-content: center;">
      <el-pagination
          v-model:current-page="pageInfo.page"
          v-model:page-size="pageInfo.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pageInfo.total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="dialogVisible" title="编辑配置" width="500px">
      <el-form :model="currentConfig" label-width="100px">
        <el-form-item label="配置键">
          <el-input v-model="currentConfig.configKey" disabled></el-input>
        </el-form-item>
        <el-form-item label="配置值">
          <el-input v-model="currentConfig.configValue"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="currentConfig.configDesc" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveConfig">保存</el-button>
      </template>
    </el-dialog>

    <!-- 公共配置弹窗 -->
    <el-dialog v-model="publicConfigVisible" title="公共配置" width="600px">
      <el-table :data="formatPublicConfigData" border max-height="400">
        <el-table-column prop="key" label="配置键" width="200"></el-table-column>
        <el-table-column prop="value" label="配置值"></el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="publicConfigVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 历史记录弹窗 -->
    <el-dialog v-model="historyVisible" title="配置历史记录" width="900px">
      <!-- 筛选条件 -->
      <el-form :model="historyFilter" inline>
        <el-form-item label="配置键">
          <el-input v-model="historyFilter.key" placeholder="请输入配置键" />
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="historyFilter.operator" placeholder="请输入操作人" />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
              v-model="historyFilter.startDate"
              type="date"
              placeholder="开始日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="至">
          <el-date-picker
              v-model="historyFilter.endDate"
              type="date"
              placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="viewHistory">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center;">
          <el-pagination
              :current-page="configStore.pageInfo.page"
              :page-size="configStore.pageInfo.size"
              :total="configStore.pageInfo.total"
              @current-change="handleHistoryPageChange"
              layout="prev, pager, next"
          />
          <el-button @click="historyVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
</style>
